package com.chwn.curiousdiary.utils;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;

import java.util.List;

/**
 * Created by Myshikin on 2017/6/8.
 */

public class ServiceUtils {
    public static boolean isServiceRunning(Context context, String className) {
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager) context.getSystemService("activity");
        List serviceList = activityManager.getRunningServices(2147483647);
        if (serviceList.size() <= 0) {
            return false;
        } else {
            for (int i = 0; i < serviceList.size(); ++i) {
                if (((ActivityManager.RunningServiceInfo) serviceList.get(i)).service.getClassName().equals(className)) {
                    isRunning = true;
                    break;
                }
            }

            return isRunning;
        }
    }

    public static void startService(Context context, Class clazz, Intent intent) {
        if (!isServiceRunning(context, clazz.getName())) {
            context.startService(intent);
        }

    }

    public static void stopService(Context context, Class clazz) {
        if (isServiceRunning(context, clazz.getName())) {
            context.stopService(new Intent(context, clazz));
        }

    }
}
